<script setup lang="ts">
import { ref, markRaw, onMounted } from "vue";
import ReCol from "@/components/ReCol";
import { useDark, randomGradient } from "./utils";
import WelcomeTable from "./components/table/index.vue";
import { ReNormalCountTo } from "@/components/ReCountTo";
import { useRenderFlicker } from "@/components/ReFlicker";
import { ChartBar, ChartLine, ChartRound } from "./components/charts";
import Segmented, { type OptionsType } from "@/components/ReSegmented";
import { getDashboardSummaryApi } from "@/api/airport/dashboard/sirDashboard";
import { UserFilled, HelpFilled, CircleCheck, StarFilled } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import { IconifyIconOffline } from "@/components/ReIcon";

defineOptions({
  name: "Welcome"
});

const { isDark } = useDark();

let curWeek = ref(1); // 0上周、1本周
const optionsBasis: Array<OptionsType> = [
  {
    label: "上周"
  },
  {
    label: "本周"
  }
];

// 新增：定义数据变量和加载状态
const loading = ref(true);
const chartData = ref([]);
const barChartData = ref([]);
const progressData = ref([]);
const latestNewsData = ref([]);
const tableData = ref([]);

// 新增：从接口获取数据
onMounted(async () => {
  try {
    loading.value = true;
    const { data } = await getDashboardSummaryApi();

    // 处理检查汇总数据，保留原有静态配置
    chartData.value = data.inspectionSummary.map((item, index) => {
      const staticConfig = [
        { icon: UserFilled, bgColor: "#effaff", color: "#41b6ff", duration: 3000 },
        { icon: HelpFilled, bgColor: "#fff5f4", color: "#e85f33", duration: 3000 },
        { icon: CircleCheck, bgColor: "#eff8f4", color: "#26ce83", duration: 3000 },
        { icon: StarFilled, bgColor: "#f6f4fe", color: "#7846e5", duration: 3000 }
      ][index] || { icon: UserFilled, bgColor: "#effaff", color: "#41b6ff", duration: 3000 };

      return { ...staticConfig, ...item };
    });

    // 处理其他数据
    barChartData.value = data.weeklyChecks;
    progressData.value = data.weeklyCompliance.reverse();
    tableData.value = data.dailySummary;

    // 处理最新动态数据
    latestNewsData.value = data.recentActivities.slice(0, 14).map(item => ({
      ...item,
      requiredNumber: Math.floor(Math.random() * 1000),
      resolveNumber: Math.floor(Math.random() * 500)
    }));
  } catch (error) {
    console.error("Failed to fetch dashboard data:", error);
  } finally {
    loading.value = false;
  }
});
</script>

<template>
  <div>
    <el-row :gutter="24" justify="space-around" v-loading="loading">
      <!-- 第一行四个方块 -->
      <re-col
        v-for="(item, index) in chartData"
        :key="index"
        v-motion
        class="mb-[18px]"
        :value="6"
        :md="12"
        :sm="12"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 80 * (index + 1)
          }
        }"
      >
        <el-card class="line-card" shadow="never">
          <div class="flex justify-between">
            <!-- 标题 -->
            <span class="text-md font-medium">
              {{ item.name }}
            </span>
            <div
              class="w-8 h-8 flex justify-center items-center rounded-md"
              :style="{
                backgroundColor: isDark ? 'transparent' : item.bgColor
              }"
            >
              <!-- 图标 -->
              <ElIcon :color="item.color" size="20">
                <component :is="item.icon" />
              </ElIcon>
            </div>
          </div>
          <div class="flex justify-between items-start mt-3">
            <div class="w-1/2">
              <!-- 总数量 -->
              <ReNormalCountTo
                :duration="item.duration"
                :fontSize="'1.6em'"
                :startVal="0"
                :endVal="item.value"
              />
              <!-- 百分比 -->
              <p class="font-medium text-green-500">{{ item.percent }}</p>
            </div>
            <!-- 曲线图 -->
            <ChartLine
              v-if="item.data.length > 1"
              class="w-1/2!"
              :color="item.color"
              :data="item.data"
            />
            <ChartRound v-else class="w-1/2!" />
          </div>
        </el-card>
      </re-col>

      <!-- 安全检查数量条形图 -->
      <re-col
        v-motion
        class="mb-[18px]"
        :value="18"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 400
          }
        }"
      >
        <el-card class="bar-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium">安全检查数量</span>
            <Segmented v-model="curWeek" :options="optionsBasis" />
          </div>
          <div class="flex justify-between items-start mt-3">
            <ChartBar
              v-if="barChartData[curWeek]"
              :requireData="barChartData[curWeek].requireData"
              :questionData="barChartData[curWeek].questionData"
            />
          </div>
        </el-card>
      </re-col>

      <!-- 检查合格率 -->
      <re-col
        v-motion
        class="mb-[18px]"
        :value="6"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 480
          }
        }"
      >
        <el-card shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium">检查合格率</span>
          </div>
          <div
            v-for="(item, index) in progressData"
            :key="index"
            :class="[
              'flex',
              'justify-between',
              'items-start',
              index === 0 ? 'mt-8' : 'mt-[2.15rem]'
            ]"
          >
            <el-progress
              :text-inside="true"
              :percentage="item.percentage"
              :stroke-width="21"
              :color="item.color"
              striped
              striped-flow
              :duration="item.duration"
            />
            <span class="text-nowrap ml-2 text-text_color_regular text-sm">
              {{ item.week }}
            </span>
          </div>
        </el-card>
      </re-col>

      <!-- 数据统计 -->
      <re-col
        v-motion
        class="mb-[18px]"
        :value="18"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 560
          }
        }"
      >
        <el-card shadow="never" class="h-[580px]">
          <div class="flex justify-between">
            <span class="text-md font-medium">数据统计</span>
          </div>
          <WelcomeTable class="mt-3" :table-data="tableData" />
        </el-card>
      </re-col>

      <!-- 最新动态 -->
      <re-col
        v-motion
        class="mb-[18px]"
        :value="6"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 640
          }
        }"
      >
        <el-card shadow="never">
          <div class="flex justify-between">
            <span class="text-md font-medium">最新动态</span>
          </div>
          <el-scrollbar max-height="504" class="mt-3">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in latestNewsData"
                :key="index"
                center
                placement="top"
                :icon="
                  markRaw(
                    useRenderFlicker({
                      background: randomGradient({
                        randomizeHue: true
                      })
                    })
                  )
                "
                :timestamp="item.date"
              >
                <p class="text-text_color_regular text-sm">
                  {{ item.deptName || '未知部门' }}---新增一条{{ item.source }} ，标题为： {{ item.title }}
                </p>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </re-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card) {
  --el-card-border-color: none;

  /* 解决概率进度条宽度 */
  .el-progress--line {
    width: 85%;
  }

  /* 解决概率进度条字体大小 */
  .el-progress-bar__innerText {
    font-size: 15px;
  }

  /* 隐藏 el-scrollbar 滚动条 */
  .el-scrollbar__bar {
    display: none;
  }

  /* el-timeline 每一项上下、左右边距 */
  .el-timeline-item {
    margin: 0 6px;
  }
}

.main-content {
  margin: 20px 20px 0 !important;
}
</style>
